import axios from 'axios'
import type { AxiosInstance } from 'axios'
import { ElLoading } from 'element-plus'
import type { ILoadingInstance } from 'element-plus/lib/el-loading/src/loading.type'

import { WJInterceptors, WJRequestConfig } from './types'
import { BASE_SHOW_LOADING } from './config'

class WJRequest {
  instance: AxiosInstance
  interceptors?: WJInterceptors
  loading?: ILoadingInstance
  showLoading?: boolean

  constructor(config: WJRequestConfig) {
    this.instance = axios.create(config)
    this.interceptors = config.interceptors
    this.showLoading = config.showLoading

    // 实例请求拦截
    this.instance.interceptors.request.use(
      this.interceptors?.requestInterceptor,
      this.interceptors?.requestInterceptorCatch
    )
    // 实例响应拦截
    this.instance.interceptors.response.use(
      this.interceptors?.responseInterceptor,
      this.interceptors?.responseInterceptorCatch
    )

    // 全局请求拦截
    this.instance.interceptors.request.use(
      (config) => {
        if (this.showLoading) {
          this.loading = ElLoading.service({
            lock: true,
            text: '正在请求数据...',
            background: 'rgba(0,0,0,.2)'
          })
        }
        return config
      },
      (error) => {
        this.loading?.close()
        console.log(error)
      }
    )

    // 全局响应拦截
    this.instance.interceptors.response.use(
      (res) => {
        this.loading?.close()
        return res.data
      },
      (error) => {
        this.loading?.close()
        console.log(error)
      }
    )
  }

  request<T = any>(config: WJRequestConfig<T>): Promise<T> {
    return new Promise((resolve, reject) => {
      // 单独的请求拦截
      if (config.interceptors?.requestInterceptor) {
        config = config.interceptors.requestInterceptor(config)
      }

      // 判断是否改变加载
      if (config.showLoading !== undefined && config?.showLoading !== BASE_SHOW_LOADING) {
        this.showLoading = config.showLoading
      } else {
        this.showLoading = BASE_SHOW_LOADING
      }

      this.instance
        .request<any, T>(config)
        .then((res) => {
          // 单独的响应拦截
          if (config.interceptors?.responseInterceptor) {
            res = config.interceptors.responseInterceptor(res)
          }
          resolve(res)
        })
        .catch((error) => {
          reject(error)
        })
    })
  }

  get<T = any>(config: WJRequestConfig<T>): Promise<T> {
    return this.request<T>({ ...config, method: 'GET' })
  }

  post<T = any>(config: WJRequestConfig<T>): Promise<T> {
    return this.request<T>({ ...config, method: 'POST' })
  }

  delete<T = any>(config: WJRequestConfig<T>): Promise<T> {
    return this.request<T>({ ...config, method: 'DELETE' })
  }

  patch<T = any>(config: WJRequestConfig<T>): Promise<T> {
    return this.request<T>({ ...config, method: 'PATCH' })
  }
}

export default WJRequest
